package com.jintoufs.web.action.tour;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jintoufs.dao.QueryFilters;
import com.jintoufs.dao.QueryRule;
import com.jintoufs.domain.constants.Constants;
import com.jintoufs.domain.constants.FullCalendar;
import com.jintoufs.domain.customer.Customer;
import com.jintoufs.domain.date.DateBean;
import com.jintoufs.domain.hotel.HotelRoom;
import com.jintoufs.domain.images.Images;
import com.jintoufs.domain.tour.TourRoute;
import com.jintoufs.domain.tour.TourRouteDay;
import com.jintoufs.domain.tour.TourRoutePrice;
import com.jintoufs.domain.travelagency.Poi;
import com.jintoufs.logAnnotation.SystemControllerLog;
import com.jintoufs.service.date.DateBeanService;
import com.jintoufs.service.image.ImageService;
import com.jintoufs.service.tour.TourRouteService;
import com.jintoufs.service.travelagency.PoiService;
import com.jintoufs.service.travelagency.TravelAgencyService;
import com.jintoufs.util.date.DateUtils;
import com.jintoufs.util.valid.ValidUtil;
import com.jintoufs.web.action.shiro.bind.annotation.CurrentUser;
import com.jintoufs.web.action.support.JqgridPage;
import com.jintoufs.web.action.support.SupportAction;
import org.apache.commons.lang.StringUtils;
import org.cosmos.modules.exception.ServiceException;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zhenghq
 * @date 2018-01-15 11:27
 */

@Controller
@Scope("prototype")
@RequestMapping("/tour/route")
public class TourRoutAction extends SupportAction{

    @Autowired private TourRouteService tourRouteService;

    @Resource
    private DateBeanService dateBeanService;
    @Resource
    private PoiService poiService;
    @Resource
    private ImageService imageService;
    @Autowired
    TravelAgencyService travelAgencyService;
    /**
     * 线路管理列表页面
     */
    @RequestMapping("/list")
    public String list(Model model,String taId) {
        model.addAttribute("taId",taId);
        model.addAttribute("ta",travelAgencyService.getTravelAgencyById(taId));
        return "tour/route/list";
    }

    /**
     * 假期列表页面
     */
    @RequestMapping("/talist")
    public String travelAgencyList(Model model,@CurrentUser Customer customer) {
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("managerId",customer.getId());
        model.addAttribute("tas",tourRouteService.getTravelAgencyListByParams(params));
        return "tour/route/list-agency";
    }

    /**
     * 查询线路信息
     */
    @RequestMapping("/query")
    @ResponseBody
    public JqgridPage query(String taId,int page, int rows, String sidx, String sord, String filters,@CurrentUser Customer customer) {
        PageHelper.startPage(page, rows);
        QueryFilters filters_ = StringUtils.isEmpty(filters)?new QueryFilters()
                :JSON.parseObject(filters, QueryFilters.class);

        QueryRule role = new QueryRule();
        role.setField("customer_id");
        role.setOp("eq");
        role.setData(customer.getId());
        filters_.getRules().add(role);
        if (!ValidUtil.isEmpty(taId)){
            role = new QueryRule();
            role.setOp("eq");
            role.setField("travel_agency_id");
            role.setData(taId);
            filters_.getRules().add(role);
        }
        filters_.setSidx(sidx);
        filters_.setSord(sord);
        List<Map<String,Object>> list = tourRouteService.getByFilter(filters_);
        PageInfo pageInfo = new PageInfo(list);
        return new JqgridPage(pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getPageNum(), pageInfo.getList());
    }

    /**
     * 新增及编辑线路页面
     */
    @RequestMapping("/input")
    public String input(Model model, String routeId,String taId) {
        initPage(model,routeId,taId);
        return "tour/route/input";
    }

    /**
     * 新增及编辑线路页面风格2
     */
    @RequestMapping("/input2")
    public String input2(Model model, String routeId,String taId) {
        initPage(model,routeId,taId);
        Map<String,Object> params = new HashMap<>();
        params.put("agencyId",taId);
        List<Map<String,Object>> pois =  poiService.getByParams(params);
        model.addAttribute("pois",pois);
        return "tour/route/input2";
    }
    /**
     * 查看线路详情
     */
    @RequestMapping("/detail")
    public String detail(Model model, String routeId,String taId) {
        initPage(model,routeId,taId);
        return "tour/route/detail";
    }
    private void initPage(Model model, String routeId,String taId){
        model.addAttribute("taId",taId);
        if(StringUtils.isNotEmpty((routeId))){
            TourRoute route = tourRouteService.getRouteById(routeId);
            Map<String,Object> params = new HashMap<>();
            params.put("valueId",route.getId());
            params.put("cover","1");
            List<Images> imagesList = imageService.selectByparams(params);
            if (!ValidUtil.isEmpty(imagesList)){
                String imgURL = imagesList.get(0).getPath();
                model.addAttribute("imgURL",imgURL);
            }
            List<Map<String,Object>> trips = new LinkedList<>();
            List<TourRouteDay> days = tourRouteService.getRouteDaysByRouteId(routeId);
            for(TourRouteDay day:days){
                Map<String,Object> dayMap = new HashMap();
                dayMap.put("day",day);
                dayMap.put("activities",tourRouteService.getRouteDayDetailsByDayId(day.getId()));
                trips.add(dayMap);
            }
            model.addAttribute("route",route);
            model.addAttribute("trips",trips);
            model.addAttribute("thisTypeList",route.getTypeId().split(","));


        }
        Map<String,Object> params = new HashMap();
        //线路类型的 parent_id = 1005002
        params.put("parentId","1005002");

        model.addAttribute("typeList",tourRouteService.getTourRouteTypeInfo(params));
    }
    /**
     * 保存线路信息
     */
    @RequestMapping("/save")
    @ResponseBody
    @SystemControllerLog(description = "保存线路")
    public AjaxMsg save(HttpServletRequest request, @CurrentUser Customer customer) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            Map<String,Object> params = getRequestParam(request);
            tourRouteService.saveRoute(params,customer);
            ajaxMsg.setCode(AjaxMsg.SUCCESS);
            ajaxMsg.setMessage("保存线路成功！");
        } catch (ServiceException se){
            se.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage(se.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("保存线路失败！");
        }
        return ajaxMsg;
    }

    /**
     * 删除线路信息
     */
    @RequestMapping("/delete")
    @ResponseBody
    @SystemControllerLog(description = "下架/上架线路")
    public AjaxMsg delete(String routeId) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            if(StringUtils.isEmpty(routeId)){
                throw new ServiceException("请传入要下架/上架的线路ID");
            }
            tourRouteService.deleteRouteInfoById(routeId);
            ajaxMsg.setCode(AjaxMsg.SUCCESS);
            ajaxMsg.setMessage("下架/上架线路成功！");
        } catch (ServiceException se){
            se.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage(se.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("下架/上架线路失败！");
        }
        return ajaxMsg;
    }

    @RequestMapping("pricealendar")
    public String priceCalendar(String routeId,Model model){
        model.addAttribute("routeId",routeId);
        return "/tour/route/pricecalendar";
    }

    @RequestMapping("/getpricecalendar/{id}")
    public void getPriceCalendar(@PathVariable String id, String start, String end, HttpServletResponse response){
        Map<String,Object> param = new HashMap<>(3);
        param.put("tourRouteId",id);
        param.put("start",start);
        param.put("end",end);
        List<FullCalendar> priceCalendar = tourRouteService.getPriceCalendar(param);

        writeInfo(response,JSON.toJSONString(priceCalendar));
    }
    /**
     * 保存线路价格信息
     * 以当前时间为准，不同时间购买价格不同
     */
    @RequestMapping("/setpricecalendar")
    @ResponseBody
    public AjaxMsg setPriceCalendar(TourRoutePrice tourRoutePrice){
        AjaxMsg ajaxMsg = new AjaxMsg();
        tourRoutePrice.setTravelAgencyId(tourRouteService.getRouteById(tourRoutePrice.getTourRouteId()).getTravelAgencyId());
        TourRoutePrice nowTourRoutePrice = tourRouteService.selectByTourRoutePrice(tourRoutePrice);
        try {
            if (!ValidUtil.isEmpty(nowTourRoutePrice)){
                tourRouteService.updatePrice(tourRoutePrice);
            }else {
                tourRoutePrice.setId(getUUID());
                tourRoutePrice.setReserve(tourRouteService.getRouteById(tourRoutePrice.getTourRouteId()).getPersonNum());
                tourRouteService.insertTourRoutePrice(tourRoutePrice);
            }
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setCode("500");
            ajaxMsg.setMessage("系统错误");
        }
        return ajaxMsg;
    }

    @RequestMapping("pricealendar2")
    public String priceCalendar2(String routeId,Model model){
        Map<String,Object> param = new HashMap<>(3);
        param.put("tourId",routeId);
        param.put("date",DateUtils.getDate("yyyy-MM"));
        List<Map<String,Object>> priceCalendar = tourRouteService.getPriceCalendar2(param);
        DateBean dateBean = dateBeanService.getLast();
        model.addAttribute("priceCalendar",JSON.toJSONString(priceCalendar));
        model.addAttribute("dateBean",dateBean.getDate());
        model.addAttribute("routeId",routeId);
        return "/tour/route/pricecalendar2";
    }

    @RequestMapping("/getpricecalendar2/{id}")
    public void getPriceCalendar2(@PathVariable String id, String date, HttpServletResponse response){
        Map<String,Object> param = new HashMap<>(1);
        param.put("tourId",id);
        param.put("date",DateUtils.getNextMonth(date,"yyyy-MM"));
        List<Map<String,Object>> priceCalendar = tourRouteService.getPriceCalendar2(param);
        writeInfo(response,JSON.toJSONString(priceCalendar));
    }

    @RequestMapping("/setpricecalendar2/{id}")
    @ResponseBody
    public AjaxMsg setPriceCalendar(@PathVariable String id,String data,String dates){
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            TourRoute tourRoute = tourRouteService.getRouteById(id);
            data = data.replace("开启","1").replace("关闭","0");
            TourRoutePrice priceData = JSON.parseObject(data,TourRoutePrice.class);
            priceData.setTourRouteId(id);
            TourRoutePrice nowTourRoutePrice;
            priceData.setTravelAgencyId(tourRoute.getTravelAgencyId());
            if (!ValidUtil.isEmpty(dates)){
                List datesList = JSON.parseObject(dates,List.class);
                for (Object date:datesList){
                    priceData.setDate(DateUtils.parseDate(date.toString(),"yyyy-MM-dd"));
                    nowTourRoutePrice = tourRouteService.selectByTourRoutePrice(priceData);
                    if (!ValidUtil.isEmpty(nowTourRoutePrice)){
                        tourRouteService.updatePrice(priceData);
                    }else {
                        priceData.setId(getUUID());
                        tourRouteService.insertTourRoutePrice(priceData);
                    }
                }
            }else {
                nowTourRoutePrice = tourRouteService.selectByTourRoutePrice(priceData);
                if (!ValidUtil.isEmpty(nowTourRoutePrice)){
                    tourRouteService.updatePrice(priceData);
                }else {
                    priceData.setId(getUUID());
                    tourRouteService.insertTourRoutePrice(priceData);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("后台发生错误。");
        }
        return ajaxMsg;
    }

    /**
     * 获取页面参数值
     */
    public Map<String,Object> getRequestParam(HttpServletRequest request){

        try {
            Map<String,Object> params = new HashMap();
            Map<String,String[]> parameters = request.getParameterMap();
            for(Map.Entry<String, String[]> entry:parameters.entrySet()){
                String[] values = entry.getValue();
                params.put(entry.getKey(), values.length>1?values:values[0]);
            }
            return params;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

    }



    @RequestMapping("notToGiveUp/{id}")
    @ResponseBody
    public AjaxMsg notToGiveUp(@PathVariable String id, String start){
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map<String,Object> params = new HashMap<>();
        params.put("tourRouteId",id);
        params.put("start",start);
        try {
            TourRoutePrice tourRoutePrice = tourRouteService.getTourRoutePrice(params);
            if (ValidUtil.isEmpty(tourRoutePrice)){
                TourRoute tourRoute = tourRouteService.getRouteById(id);
                tourRoutePrice = new TourRoutePrice();
                tourRoutePrice.setId(getUUID());
                tourRoutePrice.setTourRouteId(id);
                tourRoutePrice.setPrice(tourRoute.getTotalFee());
                tourRoutePrice.setDistributionPrice(tourRoute.getDistributionPrice());
                tourRoutePrice.setTravelAgencyId(tourRoute.getTravelAgencyId());
                tourRoutePrice.setReserve(tourRoute.getPersonNum());
                tourRoutePrice.setStatus("0");
                tourRoutePrice.setDate(DateUtils.stringToDate(start));
                tourRouteService.insertTourRoutePrice(tourRoutePrice);
            }else {
                if ("1".equals(tourRoutePrice.getStatus())||ValidUtil.isEmpty(tourRoutePrice.getStatus())){
                    tourRoutePrice.setStatus("0");
                }else {
                    tourRoutePrice.setStatus("1");
                }
                tourRouteService.updateTourRoutePrice(tourRoutePrice);
            }
        }catch (Exception e){
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("出错啦！请稍后重试。");
        }
        return ajaxMsg;
    }


    @RequestMapping("/changeStatus")
    @ResponseBody
    @SystemControllerLog(description = "更新鱼·定制产品状态")
    public AjaxMsg changeStatus(HttpServletResponse response, String valueId) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        ajaxMsg.setCode(AjaxMsg.SUCCESS);
        TourRoute tourRoute = tourRouteService.getRouteById(valueId);
        if (Constants.RES_STATUS_NORMAL.equals(tourRoute.getStatus())) {
            tourRoute.setStatus(Constants.RES_STATUS_DELETE);
        } else {
            tourRoute.setStatus(Constants.RES_STATUS_NORMAL);
        }
        tourRouteService.update(tourRoute);
        return ajaxMsg;
    }
}
